package com.bskj.kuaifu.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.bskj.common.utils.LogUtils;

public class MyFilterChain implements Filter {
	private List<MyFilter> filters;
	private Set<String> prefixIignores = new HashSet<String>();

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		LogUtils.debug("url:" + httpServletRequest.getRequestURI());

		if (canIgnore(httpServletRequest)) {
			chain.doFilter(request, response);
			return;
		}

		if (filters != null && filters.size() > 0) {
			filters.get(0).doFilter(request, response, chain);
		}
	}

	public void destroy() {
	}

	public List<MyFilter> getFilters() {
		return filters;
	}

	public void setFilters(List<MyFilter> filters) {
		this.filters = filters;
		for (int i = 0; i < filters.size() - 1; i++) {
			MyFilter filter = filters.get(i);
			filter.setNext(filters.get(i + 1));
		}
	}

	public Set<String> getPrefixIignores() {
		return prefixIignores;
	}

	public void setPrefixIignores(Set<String> prefixIignores) {
		this.prefixIignores = prefixIignores;
	}

	private boolean canIgnore(HttpServletRequest request) {
		String url = request.getRequestURI();
		String contextPath = request.getContextPath();
		for (String ignore : prefixIignores) {
			if (url.startsWith(contextPath + ignore)) {
				return true;
			}
		}
		return false;
	}
}
